package com.plugin.buildsrc

import org.gradle.BuildListener
import org.gradle.BuildResult
import org.gradle.api.Task
import org.gradle.api.execution.TaskExecutionListener
import org.gradle.api.initialization.Settings
import org.gradle.api.invocation.Gradle
import org.gradle.api.tasks.TaskState

import java.util.concurrent.TimeUnit

/**
 Task耗时监控
@Author Damon
*/
class TimesCostWatcher implements TaskExecutionListener, BuildListener {
    private long startTime
    private def timings = []
/*    @Override
     void buildStarted(Gradle gradle) {}*/
    @Override
     void settingsEvaluated(Settings settings) {}
    @Override
     void projectsLoaded(Gradle gradle) {}
    @Override
     void projectsEvaluated(Gradle gradle) {}

    @Override
     void buildFinished(BuildResult buildResult) {
        Logger.log "耗时任务表:"
        for (def timing in timings) {
            if (timing[0] >= 200) {
//                Logger.log "任务${timing[1]}  花费时间: ${timing[0]} ms"
            }
        }
    }

    @Override
     void beforeExecute(Task task) {
        startTime = System.nanoTime()
    }

    @Override
     void afterExecute(Task task, TaskState taskState) {
        if(task.getName() == "dataBindingGenBaseClasses") {
            task.toString();
        }
        def ms = TimeUnit.MILLISECONDS.convert(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
        timings.add([ms, task.path])
//        Logger.log"任务: ${task.path} 花费 ${ms} ms"
    }
}
